<template>
  <div class="content-wrapper">
    <div class="nav">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/administration-rightsSetting' }">系统设置</el-breadcrumb-item>
        <el-breadcrumb-item>权限设置</el-breadcrumb-item>
      </el-breadcrumb>
      <span><el-button type="primary" @click="showDialog(false)" v-if="isAuth('hr:role:save')">新增角色</el-button></span>
    </div>
    <div class="content">
      <el-form label-position="top">
        <el-form-item v-for="item in rightsList" :key="item.roleId">
          <template slot="label">
            <span @click="showDialog(item.roleId)" class="role-name" v-if="isAuth('hr:role:update')">{{item.roleName}}</span>
            <span class="role-name" v-else>{{item.roleName}}</span>
          </template>
          <div class="select-btn" @click="selectDingUsers(item, 300)" v-if="isAuth('hr:roleuser:setting')"><span><i class="el-icon-plus"></i></span>添加</div>
          <div v-for="(user, index) in item.user" :key="user.emplId">
            <div class="select-btn" @click="delMember(item, index)"><span><img :src="user.avatar"></span>{{user.name}}<div class="del" v-if="isAuth('hr:roleuser:setting')">移除</div></div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :title="!form.roleId ? '新增角色' : '编辑角色'"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="800px">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="roleName" :rules="[{ required: true, message: '请输入角色名称', trigger: 'blur' }]">
          <el-input v-model="form.roleName" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item size="mini" label="权限" style="margin-bottom: 0;">
          <el-tree
            :data="menuList"
            :props="{ label: 'name', children: 'children' }"
            node-key="menuId"
            ref="menuListTree"
            :default-expand-all="true"
            @check-change="handleCheckChange"
            show-checkbox>
          </el-tree>
        </el-form-item>
        <el-form-item>
          <el-popover
            placement="bottom-start"
            width="500"
            trigger="hover">
            <div>
              <div>1.普通员工权限：普通员工可见通讯录列表，可见考勤列表，可见个人详情（仅本人），履历详情（仅本人），绩效（仅本人）</div>
              <div>2.面试主管：可以编辑本部门的面试考评设置，可书写考评内容并提交。</div>
              <div>3.招聘专员：可录入面试人员，可见招聘列表，可见面试评审，可见招聘流程（不可见薪资待遇），招聘回访中可见薪资，招聘回访结束不可见薪资。</div>
              <div>4.行政总监：所有可见，所有可操作。</div>
              <div>5.人事考勤：可上传考勤列表，可编辑考勤结构。考勤只可编辑本月的，历史记录所有角色均不可编辑。人事考勤可以修改员工个人信息。</div>
              <div>6.绩效管理：可查看所有人的绩效。</div>
              <div>7.资产管理，可以登记资产，编辑资产。</div>
              <div>8.资产查看：只可查询，不可编辑。</div>
              <div>9.权限操作：可以编辑权限（管理员/CEO和行政总监默认拥有该权限）</div>
              <div>10.奖惩管理：可见积分红利汇总列表和其他员工的奖惩详情。</div>
              <div>11.红利积分管理：可见积分红利汇总列表和其他员工的红利详情。</div>
            </div>
            <el-button type="text" slot="reference">权限说明？？？</el-button>
          </el-popover>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div><el-button @click="delRole" size="mini" type="danger" v-if="form.roleId && isAuth('hr:role:delete')">删除</el-button></div>
        <div>
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="submitForm" size="mini">保存</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import { treeDataTranslate } from '@/utils'
export default {
  data () {
    return {
      menuList: [],
      rightsList: [],
      dialogVisible: false,
      form: {
        roleName: '',
        remark: '',
        menuIdList: [],
      },
    };
  },
  components: {},
  mounted () {
    this.getMenuList()
    this.getRoleList()
  },
  mixins: [dingMixin],
  methods: {
    getMenuList() {
      this.$http({
        url: this.$http.adornUrl('hr/menu/list'),
        method: 'get'
      }).then(({data}) => {
        this.menuList = treeDataTranslate(data, 'menuId')
      })
    },
    async getRoleList() {
      let {list} = await this.$httpN.postB('hr/role/page', { limit: 999 })
      let roleIdsArr = list.map( role => { return role.roleId})
      let data = await this.$httpN.postB('sys/user/listUserByRoleIds', roleIdsArr, false)
      list.forEach( role => { role.user = data[role.roleId] })
      this.rightsList = list;
    },
    selectDingUsers(role, num){
      let idArr = role.user.map(item => item.emplId)
      this.complexPicker(num, [], idArr).then((data)=>{
        this.submitUserRole(role.roleId, data);
      })
    },
    delMember(role, idx) {
      if(!this.isAuth('hr:roleuser:setting')) return
      role.user.splice(idx,1);
      this.submitUserRole(role.roleId, role.user)
    },
    async submitUserRole(roleId, usersArr) {
      let idArr = usersArr.map(item => item.emplId)
      let idStr = idArr.length > 0 ? idArr.join(',') : ''
      if( !await this.$httpN.postB('hr/role/setUserRole?roleId='+roleId+'&dingIds='+idStr) ) return
      // if( !await this.$httpN.postB('sys/user/setUserRole?roleId='+roleId+'&dingIds='+idStr) ) return
      formUtil.submitSuccess('保存成功');
      this.getRoleList()
    },
    async showDialog(roleId) {
      if(roleId === '1318068133333639166') return this.$message.error('系统管理员权限不可编辑')
      formUtil.resetData(this.form);
      if(this.$refs.form) this.$refs.form.clearValidate();
      if(this.$refs.menuListTree) this.$refs.menuListTree.setCheckedKeys([])
      if(roleId) {
        this.form = await this.$httpN.postB('hr/role/info/'+roleId)
        this.$nextTick(() => {
          this.form.menuIdList.forEach(menuId => {
            let node = this.$refs.menuListTree.getNode(menuId);
            if(node && node.isLeaf) this.$refs.menuListTree.setChecked(node, true);
          })
        })
      }
      this.dialogVisible = true;
    },
    //节点选中状态发生变化时的回调
    handleCheckChange(data, checked, indeterminate) {
      if (checked) {
        if(data.menuId === '1315850970379345928' || data.menuId === '1315850970379345929' || data.menuId === '1315850970379345930') this.$refs.menuListTree.setCheckedKeys(['1315850970379345927'].concat(this.$refs.menuListTree.getCheckedKeys()))
      }
    },
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.form.menuIdList = [].concat(this.$refs.menuListTree.getCheckedKeys(), this.$refs.menuListTree.getHalfCheckedKeys())
          if (!await this.$httpN.postB(!this.form.roleId ? 'hr/role/save' : 'hr/role/update', this.form)) return
          formUtil.submitSuccess('保存成功');
          this.dialogVisible = false;
          this.getRoleList()
        }
      })
    },
    async delRole() {
      formUtil.submitConfirm('请问您是否确认删除该角色', async ()=> {
        if(!await this.$httpN.postB('hr/role/delete', [this.form.roleId], false)) return;
        formUtil.submitSuccess('删除成功');
        this.dialogVisible = false;
        this.getRoleList();
      })
    },
  }
}
</script>

<style lang='scss' scoped>
.content-wrapper {
  min-width: 500px;
  .nav {
    display: flex;
    height: 50px;
    line-height: 50px;
    padding: 0 20px;
    justify-content: space-between;
    border-bottom: 1px solid #DCDFE6;
    .el-breadcrumb {
      display: flex;
      align-items: center;
      .el-breadcrumb__item {
        float: none;
      }
    }
  }
  .content {
    padding: 20px;
    height: calc(100vh - 50px);
    overflow: auto;
    .select-btn{
      float:left;
      font-weight: normal;
      margin-right: 5px;
      margin-top: 5px;
      width: 80px;
      height: 28px;
      border-radius: 30px;
      background: #FAFAFA;
      border: 1px solid #ECECEC;
      position: relative;
      padding-left: 21px;
      line-height: 28px;
      color: #7982A7;
      font-size: 12px;
      text-align: center;
      cursor: pointer;
      span{
        position: absolute;
        top: 1px;
        left: 1px;
        display:block;
        height: 24px;
        width: 24px;
        background: #CACACA;
        color: white;
        border-radius: 50%;
        text-align: center;
        line-height: 24px;
        img{
          width: 24px;
          height: 24px;
          border-radius: 50%;
        }
      }
      .del{
        position: absolute;
        top:0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 30px;
        color: white;
        text-align: center;
        background:rgba(130, 130, 130, 0.9);
        display: none;
      }
      &:hover{
        .del, .close{
          display: block;
        }
      }
    }
    .role-name {
      color: #409eff;
      cursor: pointer;
      &:hover {
        color: #66B1FF;
      }
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
}
</style>